<?php

namespace App\Http\Controllers\Company\English;

use App\Facades\Site;
use App\Facades\Style;
use App\Http\Controllers\Company\CommonController;
use App\Http\Requests\Company\Job\AddJobRequest;
use App\Http\Requests\Company\Job\UpdateJobRequest;
use App\Models\Common\English\EnCollTown;
use App\Models\Common\English\EnCollArea;
use App\Models\Common\English\EnCollPosition;
use App\Models\Company\CompanyBasic;
use App\Models\Company\CompanyContact;
use App\Models\Company\CompanyDepartment;
use App\Models\Company\CompanyJob;
use App\Models\Company\Points;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class JobController extends CommonController{

    /**
     * 职位发布页
     * @param Request $request
     * @return mixed
     */
    public function publish(Request $request){
        $user = auth()->guard('company')->user();
        $companyDepartment = CompanyDepartment::where('uid', $user->uid)->get();

        $companyBasic = CompanyBasic::where('uid', $user->uid)->orderBy('updatetime', 'desc')->first();

        //企业不存在时
        if(empty($companyBasic)){
            return redirect("company/register_basic");
        }
        $companyBasic->cn_region = EnCollArea::getAreaName($companyBasic->region);

        //DB::enableQueryLog();
        //$sql=DB::getQueryLog();
        //print_r($sql);
        return Style::view('company.english.jobpublish', compact('companyDepartment', 'companyBasic'));
    }

    /**
     * 数据库添加职位
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(AddJobRequest $request){
        $user = auth()->guard('company')->user();
        $input = $request->only('job_title', 'part_status', 'job_category1', 'job_category2', 'job_category3', 'job_category4', 'job_category5', 'industry', 'location1',
            'location2', 'location3', 'location4', 'location5', 'department', 'recruiting_num', 'salary_above', 'salary_below', 'description', 'education', 'work_year'
            , 'age_above', 'age_below', 'gender', 'language', 'welfare', 'contact_info','lang_type');

        $input['addtime'] = date('Y-m-d H:i:s', time());
        $input['updatetime'] = date('Y-m-d H:i:s', time());
        $input['uid'] = $user->uid;
        $input['lang_type'] = 'en';
        $CompanyBasic = CompanyBasic::where('uid', $user->uid)->orderBy('updatetime', 'desc')->first();
        $input['com_id'] = $CompanyBasic->id;
        //审核状态设置
        switch(Site::get('job_review')){
            case  1:
                $input['job_status'] = 1;
                break;
            case  2:
                $input['job_status'] = ($user->viptime >= date('Y-m-d H:i:s')) ? 1 : 0;
                break;
            case  3:
                $input['job_status'] = 0;
                break;
            default:
                $input['job_status'] = 0;
        }

        $companyJob = CompanyJob::create($input);
        if($request->contact_info == 2){
            $input = $request->only('contacts', 'mobile', 'phone', 'fax', 'email');
            $input['job_id'] = $companyJob->id;
            $input['uid'] = $user->uid;
            $input['addtime'] = date('Y-m-d H:i:s', time());
            $input['updatetime'] = date('Y-m-d H:i:s', time());
            CompanyContact::create($input);
        }

        return redirect('company/english/jobadmin');
    }

    /**
     * 职位管理
     * @param Request $request
     * @return mixed
     */
    public function admin(Request $request){
        $user = auth()->guard('company')->user();
        //获取面试通知记录
        $joblist = DB::table('company_job as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->select(
                't1.id', 't1.updatetime', 't1.com_id', 't1.recruiting_num',
                't2.company_name', 't1.job_title', 't1.contact_info', 't1.salary_above', 't1.salary_below', 't1.job_status', 't1.urgent', 't1.lang_type'
            )
            ->where('t1.uid', $user->uid)
            ->where('t1.job_status', '!=', 4)
            ->where(function($query) use ($request){
                if(strlen($request->keyWord) > 0){
                    $query->where('t1.job_title', 'like', '%' . $request->keyWord . '%');
                }
            })
            ->where(function($query) use ($request){
                if(strlen($request->job_status) > 0){
                    $query->where('t1.job_status', $request->job_status);
                }
            })
            ->where('t1.lang_type', 'en')
            ->orderBy('updatetime', 'desc')
            ->orderBy('id', 'desc')
            ->paginate(20);

        foreach($joblist as $v){
            if($v->urgent > date('Y-m-d H:i:s', strtotime('-5 day'))){
                $v->iurgent = 1;
            }else{
                $v->iurgent = 0;
            }
        }
        $job_status = $request->job_status;
        // dd($favorites);
        //设置状态
        //    $job_status =  ($this->job_status!='') ? $this->job_status : '';
        return Style::view('company.english.jobadmin', compact('joblist', 'job_status'));
    }

    /**
     * 设置状态
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function status(Request $request){
        $user = auth()->guard('company')->user();
        $allow = array(1, 2, 4); //允许的状态码
        if(in_array($request->status, $allow)){
            if(!empty($request->selected_id)){
                $companyJob = CompanyJob::select('id', 'job_status')->where('uid', $user->uid)->whereIn('id', $request->selected_id)->get();
                foreach($companyJob as $k => $v){
                    if(($v->job_status != 0 and $v->job_status != 4) or $request->status == 4){
                        $input['job_status'] = $request->status;
                        $input['xs_status'] = 0;
                        CompanyJob::where('uid', $user->uid)->where('id', $v->id)->update($input);
                    }
                }
            }elseif(!empty($request->id)){
                $companyJob = CompanyJob::select('id', 'job_status')->where('uid', $user->uid)->where('id', $request->id)->first();
                if(($companyJob->job_status != 0 and $companyJob->job_status != 4) or $request->status == 4){
                    $companyJob->job_status = $request->status;
                    $companyJob->xs_status = 0;
                    $companyJob->save();
                }
            }
            return back()->withInput();
        }else{
            return response('Error code!', 404);
        }
    }

    /**
     * 刷新职位
     * @param Request $request
     * @return $this
     */
    public function refresh(Request $request){
        $user = auth()->guard('company')->user();
        if(!empty($request->selected_id)){
            $companyJob = CompanyJob::select('id', 'job_status')->where('uid', $user->uid)->whereIn('id', $request->selected_id)->get();
            foreach($companyJob as $k => $v){
                $input['updatetime'] = date('Y-m-d H:i:s');
                $input['xs_status'] = 0;
                CompanyJob::where('uid', $user->uid)->where('id', $v->id)->update($input);
            }
        }elseif(!empty($request->id)){
            $companyJob = CompanyJob::select('id', 'job_status')->where('uid', $user->uid)->where('id', $request->id)->first();
            $companyJob->updatetime = date('Y-m-d H:i:s');
            $companyJob->xs_status = 0;
            $companyJob->save();
        }
        if($request->ajax()){
            return response()->json(['status' => 200, 'message' => 'Refresh success']);
        }else{
            return back()->withInput()->with('info', "Refresh success");
        }
    }

    /**
     * 职位加急
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function urgent(Request $request){
        $user = auth()->guard('company')->user();
        //获取积分剩余个数
        if($user->viptime > date('Y-m-d H:i:s', time())){//会员优先使用会员积分
            $integralv = $user->vip_integral;
            $feld = "vip_integral";
            if($integralv < 10){
                if($user->integral > $integralv){
                    $integralv = $user->integral;
                    $feld = "integral";
                }
            }
        }else{
            $integralv = $user->integral;
            $feld = "integral";
        }

        if($integralv < 10){
            if($request->ajax()){
                return response()->json(['status' => 601, 'message' => "Urgent success, you still have points" . $integralv . "A!"]);
            }else{
                return back()->withInput()->with('info', "Urgent success, you still have points" . $integralv . "A!");
            }
        }else{
            if(!empty($request->id)){
                $input['urgent'] = date('Y-m-d H:i:s', time());
                $input['xs_status'] = 0;
                CompanyJob::where('uid', $user->uid)->where('id', $request->id)->update($input);
                $user->{$feld} = $integralv - 10;
                $user->save();
            }
            if($request->ajax()){
                return response()->json(['status' => 200, 'message' => "Urgent success, you still have points" . $user->{$feld} . "A!"]);
            }else{
                return back()->withInput()->with('info', "Urgent success, you still have points" . $user->{$feld} . "A!");
            }
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id, Request $request){
        $user = auth()->guard('company')->user();
        $companyBasic = CompanyBasic::where('uid', $user->uid)->orderBy('updatetime', 'desc')->first();
        $companyDepartment = CompanyDepartment::where('uid', $user->uid)->get();
        $companyJob = CompanyJob::where('uid', $user->uid)->where('id', $id)->first();
        //工作岗位转中文
        $companyJob->cn_jobsort .= $companyJob->job_category1 ? EnCollPosition::getPosName($companyJob->job_category1) : '';
        $companyJob->cn_jobsort .= $companyJob->job_category2 ? '+' . EnCollPosition::getPosName($companyJob->job_category2) : '';
        $companyJob->cn_jobsort .= $companyJob->job_category3 ? '+' . EnCollPosition::getPosName($companyJob->job_category3) : '';
        $companyJob->cn_jobsort .= $companyJob->job_category4 ? '+' . EnCollPosition::getPosName($companyJob->job_category4) : '';
        $companyJob->cn_jobsort .= $companyJob->job_category5 ? '+' . EnCollPosition::getPosName($companyJob->job_category5) : '';
        //工作地区转中文
        $companyJob->cn_workplace .= (strlen($companyJob->location1) == 8) ? '+' . EnCollTown::getTownName($companyJob->location1) : EnCollArea::getAreaName($companyJob->location1);
        $companyJob->cn_workplace .= (strlen($companyJob->location2) == 8) ? '+' . EnCollTown::getTownName($companyJob->location2) : EnCollArea::getAreaName($companyJob->location2);
        $companyJob->cn_workplace .= (strlen($companyJob->location3) == 8) ? '+' . EnCollTown::getTownName($companyJob->location3) : EnCollArea::getAreaName($companyJob->location3);
        $companyJob->cn_workplace .= (strlen($companyJob->location4) == 8) ? '+' . EnCollTown::getTownName($companyJob->location4) : EnCollArea::getAreaName($companyJob->location4);
        $companyJob->cn_workplace .= (strlen($companyJob->location5) == 8) ? '+' . EnCollTown::getTownName($companyJob->location5) : EnCollArea::getAreaName($companyJob->location5);
        $type = $request->type;
        $companyContact = CompanyContact::where('uid', $user->uid)->where('job_id', $companyJob->id)->first();

        return Style::view('company.english.jobEdit', compact('companyDepartment', 'companyJob', 'companyBasic', 'companyContact', 'type'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateJobRequest $request, $id){
        $user = auth()->guard('company')->user();
        $companyJob = CompanyJob::select('id')->where('uid', $user->uid)->where('id', $id)->first();
        if($companyJob->id){
            $input = $request->only('job_title', 'part_status', 'job_category1', 'job_category2', 'job_category3', 'job_category4', 'job_category5', 'industry', 'location1',
                'location2', 'location3', 'location4', 'location5', 'department', 'recruiting_num', 'salary_above', 'salary_below', 'description', 'education', 'work_year'
                , 'age_above', 'age_below', 'gender', 'language', 'welfare', 'contact_info', 'lang_type');
            $input['updatetime'] = date('Y-m-d H:i:s', time());
            //审核状态设置
            switch(Site::get('job_review')){
                case  1:
                    $input['job_status'] = 1;
                    break;
                case  2:
                    $input['job_status'] = ($user->viptime >= date('Y-m-d H:i:s')) ? 1 : 0;
                    break;
                case  3:
                    $input['job_status'] = 0;
                    break;
                default:
                    $input['job_status'] = 0;
            }
            $input['xs_status'] = 0;
            $input['lang_type'] = 'en';
            CompanyJob::where('id', $id)->where('uid', $user->uid)->update($input);

            if($request->contact_info == 2){
                $companyContact = CompanyContact::where('uid', $user->uid)->where('job_id', $id)->first();
                $input = $request->only('contacts', 'mobile', 'phone', 'fax', 'email');
                if(!empty($companyContact->id)){
                    $input['updatetime'] = date('Y-m-d H:i:s', time());
                    CompanyContact::where('job_id', $id)->where('uid', $user->uid)->update($input);
                }else{
                    $input['job_id'] = $companyJob->id;
                    $input['uid'] = $user->uid;
                    $input['addtime'] = date('Y-m-d H:i:s', time());
                    $input['updatetime'] = date('Y-m-d H:i:s', time());
                    CompanyContact::create($input);
                }
            }
        }
        return redirect('company/english/jobadmin');
    }

    /**
     * 智能刷新
     * @param Request $request
     */
    function insertData($arr, $request){
        //插入数据库
        if(count($arr) > 0){
            $array = [];
            foreach($arr as $v){
                $array[] = [
                    'com_uid' => $request->com_uid,
                    'uptime' => $v,
                    'created_at' => date('Y-m-d H:i:s', time()),
                    'updated_at' => date('Y-m-d H:i:s', time())
                ];
            }
            DB::table('points')->insert($array);
        }
    }

    /**
     * 智能刷新
     * @param Request $request
     */
    function intelligent(Request $request){
        $number = !empty($request->days) ? $request->days * 3 * 5 : 0;//需要积分的数量
        //会员积分数量
        $userInfo = auth()->guard('company')->user();
        if(empty($userInfo)){
            return false;
        }
        $integralNumber = $userInfo->integralNumber();

        if($integralNumber > $number){
            //扣除积分数
            $userInfo->integralDeduct($number);
            //选择套餐的天数
            $days = $request->days;
            $hourly = [19, 15, 11, 7];
            $number = 3;
            $arr = [];
            $points = Points::where('com_uid', $request->com_uid)->orderBy('uptime', 'desc')->first();
            if(empty($points)){
                for($j = 0; $j < $days; $j++){
                    //当前天
                    if($j == 0){
                        //当前时间
                        $curr_time = date('Y-m-d ', time());
                        //当前的小时
                        $hour = date("G");
                        //当前以晚上19点为刷新时间
                        $curr_hour = 19;
                        if($hour >= 7 && $hour < $curr_hour){
                            $number = (integer)ceil(($curr_hour - $hour) / 4);
                        }else{
                            $number = 0;
                        }
                        if($number > 0){
                            for($i = $number - 1; $i >= 0; $i--){
                                if($i == ($number - 1)){
                                    $start_time = date('Y-m-d H:i:s', time());
                                }else{
                                    $start_time = $curr_time . $hourly[$i + 1] . ':00:00';
                                }
                                $end_time = $curr_time . $hourly[$i] . ':00:00';
                                $arr[] = rand_time($start_time, $end_time);
                            }
                        }
                    }else{
                        $number = 3;
                        //下一天
                        $curr_time = date("Y-m-d", strtotime("+" . $j . " day"));
                        for($i = $number - 1; $i >= 0; $i--){
                            $start_time = $curr_time . $hourly[$i + 1] . ':00:00';
                            $end_time = $curr_time . $hourly[$i] . ':00:00';
                            $arr[] = rand_time($start_time, $end_time);
                        }
                    }
                }
                //插入数据库
                $this->insertData($arr, $request);
            }else{
                $expireDate = substr($points->uptime, 0, 10);
                for($j = 0; $j < $days; $j++){
                    //原基础上下一天
                    $curr_time = date('Y-m-d', strtotime("+" . ($j + 1) . " day", strtotime($expireDate)));
                    for($i = $number - 1; $i >= 0; $i--){
                        $start_time = $curr_time . $hourly[$i + 1] . ':00:00';
                        $end_time = $curr_time . $hourly[$i] . ':00:00';
                        $arr[] = rand_time($start_time, $end_time);
                    }
                }
                //插入数据库
                $this->insertData($arr, $request);
            }
            return response()->json(['status' => 0, 'msg' => 'Job smart auto refresh settings successfully']);
        }else{
            return response()->json(['status' => 1, 'msg' => 'The settings failed. The number of points may not be enough. Please recharge it first']);
        }
    }
}